package com.zhx.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: web-springboot
 * @author: zhx
 * @create: 2021-05-22 21:19
 * 用户已经登陆，过滤/user和/user/index.html,因为这里拦截器拦不到
 **/
@Component //交给容器
@WebFilter(urlPatterns = {"/user/","/user/index.html","/user/loginCheck.html"}) //拦截路径
public class LoginFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("初始化登陆过滤");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //执行过滤方法，每次拦截到的请求，都会执行这个方法
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"+request.getServerPort()+request.getContextPath();
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user!=null){ //说明已经登陆了
            response.sendRedirect(basePath + "/user/toLoginSuccessPage.html");
        }
        //放行请求，放给下一个过滤器
        filterChain.doFilter(request, response);
        System.out.println("结束了登陆过滤器，耗时："+(System.currentTimeMillis()-start));
    }

    @Override
    public void destroy() {
        System.out.println("结束了登陆过滤");
    }
}
